package com.clothes.aweiDoExercises.aop;

import com.clothes.aweiDoExercises.annotation.HotKeyCheck;
import com.clothes.aweiDoExercises.common.ResultUtils;
import com.clothes.aweiDoExercises.constant.HotKeyConstant;
import com.clothes.aweiDoExercises.model.dto.questionBank.QuestionBankQueryRequest;
import com.jd.platform.hotkey.client.callback.JdHotKeyStore;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * hotkey的切面类实现自动添加缓存
 */
@Aspect //标记当前类是切面类
@Component
public class HotKeyInterceptor {

    //指定拦截进行了自定义注解的方法
    @Pointcut("@annotation(com.clothes.aweiDoExercises.annotation.HotKeyCheck)")
    public void hotKeyCachePointcut() {
    }

    @Around("hotKeyCachePointcut()")
    public Object cacheAround(ProceedingJoinPoint joinPoint) throws Throwable {
        // 获取注解和方法信息
        Method method = ((MethodSignature) joinPoint.getSignature()).getMethod();
        HotKeyCheck hotKeyCache = method.getAnnotation(HotKeyCheck.class);

        // 从参数中提取ID
        Object[] args = joinPoint.getArgs();
        Long id = extractId(args, hotKeyCache.type());
        if (id == null) return joinPoint.proceed();

        // 根据缓存类型生成不同的缓存键
        String key = generateCacheKey(id, hotKeyCache.type());
        
        // 检查缓存
        if (JdHotKeyStore.isHotKey(key)) {
            Object cachedData = JdHotKeyStore.get(key);
            if (cachedData != null) {
                return ResultUtils.success(cachedData);
            }
        }

        // 缓存未命中，执行原方法
        Object result = joinPoint.proceed();

        // 缓存结果
        if (result != null) {
            JdHotKeyStore.smartSet(key, result);
        }

        return result;
    }

    // 从参数中提取ID
    private Long extractId(Object[] args, String type) {
        if (args == null || args.length == 0) return null;

        Object firstArg = args[0];
        if (firstArg instanceof QuestionBankQueryRequest) {
            return ((QuestionBankQueryRequest) firstArg).getId();
        } else if (firstArg instanceof Long) {
            return (Long) firstArg;
        }
        return null;
    }

    // 根据类型生成缓存键
    private String generateCacheKey(Long id, String type) {
        switch (type) {
            case HotKeyConstant.QUESTION:
                return HotKeyConstant.QUESTION_HOT_KEY + id;
            case HotKeyConstant.QUESTION_BANK:
                return HotKeyConstant.QUESTION_BANK_HOT_KEY + id;
            case HotKeyConstant.QUESTION_PAGE:
                return HotKeyConstant.QUESTION_PAGE_HOT_KEY + id;
            default:
                return HotKeyConstant.QUESTION_BANK_HOT_KEY + id;
        }
    }
}